package com.train.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.user.domain.Post;
import com.train.user.domain.SysPostTopicRelation;
import com.train.user.domain.SysTopic;
import com.train.user.service.PostService;
import com.train.user.mapper.PostMapper;
import com.train.user.service.SysPostTopicRelationService;
import com.train.user.service.SysTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
* @author train
* @description 针对表【sys_post(用户动态表)】的数据库操作Service实现
* @createDate 2025-10-24 16:01:41
*/
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post>
    implements PostService {

    @Autowired
    private SysTopicService sysTopicService;

    @Autowired
    private SysPostTopicRelationService sysPostTopicRelationService;

    @Override
    @Transactional
    public Post createPost(Post post) {
        // 设置默认值
        post.setLikeCount(0L);
        post.setCommentCount(0L);
        post.setCollectCount(0L);
        post.setShareCount(0L);
        post.setViewCount(0L);
        post.setStatus("0"); // 默认状态为正常
        post.setCreateTime(new Date());
        post.setUpdateTime(new Date());
        
        // 保存动态
        save(post);
        return post;
    }

    @Override
    public Post createPostWithTopics(Post post, List<Long> topicIds, List<SysTopic> topics) {
        // 1. 验证话题是否存在
        if (topicIds != null && !topicIds.isEmpty()) {
            for (Long topicId : topicIds) {
                SysTopic topic = sysTopicService.getById(topicId);
                if (topic == null) {
                    throw new RuntimeException("话题ID " + topicId + " 不存在");
                }
                if ("1".equals(topic.getStatus())) {
                    throw new RuntimeException("话题 " + topic.getTopicName() + " 已被禁用");
                }
    }
        }
        // 2. 创建动态
        Post createdPost = createPost(post);

        // 3. 创建动态话题关联
        if (topicIds != null && !topicIds.isEmpty()) {
            for (Long topicId : topicIds) {
                SysPostTopicRelation relation = new SysPostTopicRelation();
                relation.setPostId(createdPost.getPostId());
                relation.setTopicId(topicId);
                relation.setCreateBy(post.getCreateBy());
                relation.setCreateTime(new Date());
                sysPostTopicRelationService.save(relation);

                // 增加话题的动态数
                SysTopic topic = sysTopicService.getById(topicId);
                topic.setPostCount(topic.getPostCount() == null ? 1L : topic.getPostCount() + 1);
                sysTopicService.updateById(topic);
            }
        }
        if (!topics.isEmpty()){
            for (SysTopic topic : topics) {
                LambdaQueryWrapper<SysTopic> eq = new LambdaQueryWrapper<SysTopic>()
                        .eq(SysTopic::getTopicName, topic.getTopicName());
                if (sysTopicService.getOne(eq) != null) {
                    throw new RuntimeException("话题 " + topic.getTopicName() + " 已存在");
                }
                topic.setCreateBy(post.getCreateBy());
                topic.setUpdateBy(post.getCreateBy());
                sysTopicService.save(topic);
                SysPostTopicRelation relation = new SysPostTopicRelation();
                relation.setPostId(createdPost.getPostId());
                relation.setTopicId(topic.getTopicId());
                relation.setCreateBy(post.getCreateBy());
                relation.setCreateTime(new Date());
                sysPostTopicRelationService.save(relation);

                // 增加话题的动态数
                SysTopic topic1 = sysTopicService.getById(topic.getTopicId());
                topic1.setPostCount(topic.getPostCount() == null ? 1L : topic.getPostCount() + 1);
                sysTopicService.updateById(topic1);
            }
        }
        return createdPost;
    }


    @Override
    @Transactional
    public Post updatePost(Post post) {
        // 验证动态是否存在且属于当前用户
        Post existingPost = getById(post.getPostId());
        if (existingPost == null) {
            throw new RuntimeException("动态不存在");
        }
        
        // 只有发布者才能编辑动态
        if (!ObjectUtils.isEmpty(post.getUserId()) && !post.getUserId().equals(existingPost.getUserId())) {
            throw new RuntimeException("无权限编辑该动态");
        }
        
        // 更新时间和更新者
        post.setUpdateTime(new Date());
        
        // 更新动态
        updateById(post);
        return getById(post.getPostId());
    }

    @Override
    @Transactional
    public boolean deletePost(Long postId, Long userId) {
        // 验证动态是否存在且属于当前用户
        Post post = getById(postId);
        if (post == null) {
            throw new RuntimeException("动态不存在");
        }
        
        // 只有发布者才能删除动态
        if (!post.getUserId().equals(userId)) {
            throw new RuntimeException("无权限删除该动态");
        }
        
        // 软删除：更新状态为禁用
        post.setStatus("2");
        post.setUpdateTime(new Date());
        return updateById(post);
    }

    @Override
    public Post getPostById(Long postId) {
        Post post = getById(postId);
        if (post == null || "2".equals(post.getStatus())) {
            throw new RuntimeException("动态不存在或已被删除");
        }
        return post;
    }

    @Override
    @Transactional
    public Long incrementViewCount(Long postId) {
        Post post = getById(postId);
        if (post == null) {
            throw new RuntimeException("动态不存在");
        }
        
        // 增加浏览数
        post.setViewCount(post.getViewCount() + 1);
        updateById(post);
        return post.getViewCount();
    }

    @Override
    public IPage<Post> getUserPosts(Page<Post> page, Long userId, String orderBy) {
        LambdaQueryWrapper<Post> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Post::getUserId, userId)
                   .eq(Post::getStatus, "0"); // 只查询正常状态的动态
        
        // 排序
        if ("create_time_asc".equals(orderBy)) {
            queryWrapper.orderByAsc(Post::getCreateTime);
        } else {
            // 默认按创建时间降序
            queryWrapper.orderByDesc(Post::getCreateTime);
        }
        
        return page(page, queryWrapper);
    }

    @Override
    @Transactional
    public boolean incrementLikeCount(Long postId) {
        // 使用updateWrapper进行更新，避免先查询后更新带来的并发问题
        // 将影响行数转换为boolean
        int affectedRows = this.baseMapper.incrementLikeCount(postId);
        return affectedRows > 0;
    }

    @Override
    @Transactional
    public boolean decrementLikeCount(Long postId) {
        // 使用updateWrapper进行更新，避免先查询后更新带来的并发问题
        // 确保点赞数不会小于0
        int affectedRows = this.baseMapper.decrementLikeCount(postId);
        return affectedRows > 0;
    }

    @Override
    @Transactional
    public boolean incrementCommentCount(Long postId) {
        // 使用updateWrapper进行更新，避免先查询后更新带来的并发问题
        int affectedRows = this.baseMapper.incrementCommentCount(postId);
        return affectedRows > 0;
    }

    @Override
    public IPage<Post> getPosts(Page<Post> page, String status, String orderBy) {
        LambdaQueryWrapper<Post> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果指定了状态，添加状态过滤
        if (!ObjectUtils.isEmpty(status)) {
            queryWrapper.eq(Post::getStatus, status);
        } else {
            // 默认只查询正常状态的动态
            queryWrapper.eq(Post::getStatus, "0");
        }
        
        // 排序
        if ("create_time_asc".equals(orderBy)) {
            queryWrapper.orderByAsc(Post::getCreateTime);
        } else if ("view_count_desc".equals(orderBy)) {
            queryWrapper.orderByDesc(Post::getViewCount);
        } else if ("like_count_desc".equals(orderBy)) {
            queryWrapper.orderByDesc(Post::getLikeCount);
        } else {
            // 默认按创建时间降序
            queryWrapper.orderByDesc(Post::getCreateTime);
        }
        
        return page(page, queryWrapper);
    }
    
    @Override
    public List<Post> selectPosts(LocalDateTime createTime, Long postId) {
        return baseMapper.selectPosts(createTime, postId);
    }
    
    @Override
    public List<Post> selectPostsByTopicId(Long topicId, LocalDateTime createTime, Long postId) {
        return baseMapper.selectPostsByTopicId(topicId, createTime, postId);
    }

    @Override
    public Post createPostAndTopics(Post post, List<Topic> topics) {
        return null;
    }
}